package org.smart4j.framework.core;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.smart4j.framework.common.bean.Data;
import org.smart4j.framework.common.bean.Handler;
import org.smart4j.framework.common.bean.Param;
import org.smart4j.framework.common.bean.View;
import org.smart4j.framework.common.helper.*;
import org.smart4j.framework.common.util.JsonUtil;
import org.smart4j.framework.common.util.ReflectionUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 请求分发处理器
 *
 * @author YooLin1c
 * @version 1.0.0
 * @since 2018-01-30 20:43
 */
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        SmartLoader.init();
        //获取ServletContext对象（用于注册Servlet）
        ServletContext servletContext = config.getServletContext();
        //注册处理JSP的Servlet
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigHelper.getAppJspPath().concat("*"));
        //注册处理静态资源的默认Servlet
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath().concat("*"));
        UploadHelper.init(servletContext);
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求方法和请求路径
        String requestMethodName = request.getMethod().toLowerCase();
        String requestPath = request.getPathInfo();
        if ("/favicon.ico".equals(requestPath)) {
            return;
        }
        try {
            ServletHelper.init(request, response);
            //获取Action处理器
            Handler handler = ControllerHelper.getHandler(requestMethodName, requestPath);
            //通过Bean容器获取处理器的实例
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerInstance = BeanHelper.getBean(controllerClass);
            //获取request域中的参数
            Param param;
            if (UploadHelper.isMultipart(request)) {
                param = UploadHelper.getParam(request).get();
            } else {
                param = RequestHelper.getParam(request);
            }
            //获取处理方法
            Method actionMethod = handler.getActionMethod();
            //反射执行处理方法获取返回值
            Object result;
            //避免Param参数必须传
            if (param.isEmpty()) {
                result = ReflectionUtil.invokeMethod(controllerInstance, actionMethod, param);
            } else {
                result = ReflectionUtil.invokeMethod(controllerInstance, actionMethod);
            }
            //返回值属于视图
            if (result instanceof View) {
                handleView((View) result, request, response);
            //返回值属于Json数据类型
            } else if (result instanceof Data) {
                handleData((Data) result, response);
            }
        } finally {
            ServletHelper.destroy();
        }
    }

    private void handleData(Data data, HttpServletResponse response) throws IOException {
        Object model = data.getModel();
        if (Objects.nonNull(model)) {
            //response回写JSON数据
            String jsonResult = JsonUtil.toJson(model);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(jsonResult);
            writer.flush();
            writer.close();
        }
    }

    private void handleView(View view, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String path = view.getPath();
        if (StringUtils.isNotBlank(path)) {
            //重定向
            if (path.startsWith("redirect:")) {
                path = path.replace("redirect:", "");
                response.sendRedirect(request.getContextPath().concat(path));
                //请求转发
            } else {
                //获取视图模型
                Map<String, Object> model = view.getModel();
                if (MapUtils.isNotEmpty(model)) {
                    //将视图模型添加至request域中
                    for (Map.Entry<String, Object> entry : model.entrySet()) {
                        request.setAttribute(entry.getKey(), entry.getValue());
                    }
                }
                request.getRequestDispatcher(ConfigHelper.getAppJspPath().concat(path)).forward(request, response);
            }
        }
    }
}
